<?php
// include config
require_once (dirname(__FILE__).'/include/config.inc.php');
//include class
require_once (dirname(__FILE__).'/class/parameters.inc.php');
require_once (dirname(__FILE__).'/class/types.inc.php');


class APIs{
	private $token = 'EB818C5C-63DE-41E4-8D9D-8790F3D6C75D';
	private $order = Orders::ApiListAll;
	private $type = OutputType::json;
	private $database;
	function __construct(){
		$this->database = new db(DB_HOST,DB_USER,
			DB_PASSWORD,DB_NAME);
	}
	# 错误信息集
	public function onMessage($code){
		$str = "";
		switch ($code)
		{
			case 0:
			  $str = "{\"error\":\"have not access to this page.\"}";
			  break;
			case 1:
			  $str = "{\"error\":\"No command.\"}";
			  break;
			case 2:
			  $str = "{\"error\":\"No data.\"}";
			  break;
			case 99:
			  $str = "{\"info\":\"Complated.\"}";
			  break;
			default:
			  $str = "{\"error\":\"Unknown error.\"}";
		}
		return $str;
	}
	# 通过ID来删除销售记录
	private function dbDeleteSoldDataBySoldId(){
		$data = $_REQUEST[APIsParameter::postData];
		$data = json_decode(str_replace("\\","",$data));

		$id = $data->id;
		try{
			$sql = "DELETE FROM cs2_sold 
			WHERE soldId = $id;";
			$this->database->delete($sql);
			$lv = $this->dbSoldList();
		}catch (Exception $e) {
			$lv = null;
		}
		return $lv;
	}
	# 获取银行数据列表 用于 SELECT 标签
	private function dbBankListAllForSelect(){
		# important
		$lv;
		try{
			$sql = "SELECT bankId AS `value` , CONCAT(bank,'[',bankno,']',name) AS `item`
				FROM cs2_bank WHERE (bankId > 2) ORDER BY bank DESC;";
			$lv = $this->database->select($sql);
		}catch (Exception $e) {
			$lv = null;
		}
		return $lv;
	}
	# 获取产品数据列表 用于 SELECT 标签
	private function dbProductListAllForSelect(){
		$lv = null;
		try{
			$sql = "SELECT prodId AS `value`,CONCAT(name,'[',model,']') AS `item` 
				FROM cs2_prod ORDER BY model ASC;";
			$lv = $this->database->select($sql);
		}catch (Exception $e) {
			
		}
		return $lv;
	}
	# 添加发货数据
	private function dbSoldSend(){
		
		$data = $_REQUEST[APIsParameter::postData];
		$data = json_decode(str_replace("\\","",$data));

		$id = $data->id;
		$transport = $data->transport;
		$sendno = $data->sendno;
		$realFee = $data->realFee;
		
		try{
			$sql = "UPDATE cs2_sold SET 
				transport=$transport ,sendno='$sendno' ,realFee=$realFee ,status=1
				WHERE soldId = $id;";
			$this->database->update($sql);
			
			$lv = $this->dbSoldList();
		}catch (Exception $e) {
			$lv = null;
		}
		return $lv;
	}
	# 通过ID来获取销售数据
	private function dbSoldDataById(){
		if(!isset($_REQUEST[APIsParameter::postData]))
			return;
		$data = $_REQUEST[APIsParameter::postData];
		$data = json_decode(str_replace("\\","",$data));

		$id = $data->id;
		$sGuid = $data->sGuid;
		
		try{
			$sql = "SELECT `cs2_sold`.*,
				CONCAT(`cs2_bank`.`bank`,'[',`cs2_bank`.`bankno`,']',`cs2_bank`.`name`) AS `bank`,
				IFNULL(
					(SELECT COUNT(*) 
						FROM `cs2_slist` WHERE `cs2_sold`.`sGuid` = `cs2_slist`.`sGuid`),0) AS prodCnt,
				IFNULL(
					(SELECT SUM(`soldPrice`) 
						FROM `cs2_slist` WHERE `cs2_sold`.`sGuid` = `cs2_slist`.`sGuid`),0) AS prodPrice
				FROM cs2_sold 
				LEFT JOIN (cs2_bank) ON (cs2_bank.bankId = cs2_sold.bankId)
				
				WHERE soldId = $id;";
				
			$lv = $this->database->get_one($sql);
			//	
			$sql = "SELECT slistId,sGuid,CONCAT(`cs2_prod`.`name`,'[',`cs2_prod`.`model`,']') AS productName,product,id,soldPrice FROM cs2_slist 
				LEFT JOIN (cs2_prod) ON (cs2_prod.prodId = cs2_slist.product)
			WHERE sGuid='$sGuid'";
			
			$lv["products"] = $this->database->select($sql);
			
		}catch (Exception $e) {
			$lv = null;
		}
		return $lv;
	}
	# 销售数据的数量
	private function dbSoldLen(){
		$lv = null;
		try {
		
			$sql = "SELECT COUNT(*) as cnt FROM cs2_sold ;";
				
			$lv = $this->database->select($sql);
			
		} catch (Exception $e) {
			$lv = null;
		}
		
		return $lv;
	}
	# 销售数据列表
	private function dbSoldList($type=SoldListType::all,$page=1){
		#尚未处理type参数信息
		if(isset($_REQUEST[APIsParameter::postData])){
			$data = $_REQUEST[APIsParameter::postData];
			$data = json_decode(str_replace("\\","",$data));
			$page = $data->page;
		}
		
		$lv = null;
		try {
		
			$sql = "SELECT `cs2_sold`.*,
				CONCAT(`cs2_bank`.`bank`,'[',`cs2_bank`.`bankno`,']',`cs2_bank`.`name`) AS `bank`,
				IFNULL(
					(SELECT COUNT(*) 
						FROM `cs2_slist` WHERE `cs2_sold`.`sGuid` = `cs2_slist`.`sGuid`),0) AS prodCnt,
				IFNULL(
					(SELECT SUM(`soldPrice`) 
						FROM `cs2_slist` WHERE `cs2_sold`.`sGuid` = `cs2_slist`.`sGuid`),0) AS prodPrice
				FROM cs2_sold 
				LEFT JOIN (cs2_bank) ON (cs2_bank.bankId = cs2_sold.bankId)
				ORDER BY `cs2_sold`.`soldId` DESC LIMIT " .
				($page-1) * GLOBAL_PAGE_SIZE." , ".GLOBAL_PAGE_SIZE.";";
				
			$lv = $this->database->select($sql);
			
		} catch (Exception $e) {
			$lv = null;
		}
		
		return $lv;
	}
	
	# 登记销售资料
	private function dbAddNewSaleData(){
		if(!isset($_REQUEST[APIsParameter::postData])){
			//echo $this->onMessage(2);
			return;
		}
		$type = OutputType::json;
		//$data = $_GET[APIsParameter::postData];
		// 判断数据格式
		if(isset($_REQUEST[APIsParameter::postType])){
			// xml or json only.
			$type = $_REQUEST[APIsParameter::postType];
		}
			
		$data = $_REQUEST[APIsParameter::postData];
		$data = json_decode(str_replace("\\","",$data));
		$date = $data->date;
		$auctionId = $data->auctionId;
		$bankId = $data->bankId;
		$fee = $data->fee;
		$feeType = $data->feeType;
		$addrZip = $data->addrZip;
		$addrAddress = $data->addrAddress;
		$addrName = $data->addrName;
		$addrTel = $data->addrTel;
		$adminId = $data->adminId;
		$sGuid = basic::newGuid();
		$arrProd = $data->prodArray;
		$meno = $data->meno;
		
		try {
			$sql = "INSERT INTO cs2_sold 
				(`date`, `auctionId`,`bankId`, `fee`,`feeType`,`addrZip`,
					`addrAddress`,`addrName`,`addrTel`,`sGuid`,`status`,`adminId`,`meno`) 
				VALUES('$date','$auctionId',$bankId,$fee,$feeType,'$addrZip',
					'$addrAddress','$addrName','$addrTel','$sGuid',0,$adminId,'$meno')";
			
			$this->database->insert($sql);
			
			$sql = "INSERT INTO cs2_slist(`sGuid`, `product`, `id`,`soldPrice`) 
				VALUES ";
			$cnt = count($arrProd);
			for($i=0; $i<$cnt; $i++){
				$id = $arrProd[$i]->id;
		  		$product = $arrProd[$i]->product;
		  		$soldPrice = $arrProd[$i]->soldPrice;
		  		
		  		$sql=$sql."('$sGuid',$product,'$id',$soldPrice)";
		  		
		  		if($i<$cnt-1)
					$sql=$sql.",";
				else
					$sql=$sql.";";
			}
			$this->database->insert($sql);
			
			$lv = $this->dbSoldList();
			
		} catch (Exception $e) {
			$lv = null;
		}
		
		return $lv;
	}
	
	private function ApiListAll(){
		$arr = array();
		$arrNames = get_class_methods(new APIs());
		foreach ($arrNames as $row) {
			if(substr($row,0,2) == "db")
				$arr[] = array("className"=>$row);
		}
		return $arr;
	}
	
	# 输出中心
	private function onSetOutput($data,$type=OutputType::json){
		switch ($type)
		{
			case OutputType::json:
				header("Content-type: application/json; charset=utf-8");
			  	print_r(json_encode($data));
			  	break;
			case OutputType::xml:
				$writer= new XMLWriter();
				$writer->openURI('php://output');
				$writer->startDocument('1.0', 'UTF-8');
				$writer->startElement("root");
				$writer->writeAttribute("order", $this->order);
				$writer->writeAttribute("date", date(DATE_RFC822));
				# 读取行
				foreach ($data as $row) {
					$writer->startElement("data");
					$keys = array_keys($row);
					# 解析列
					foreach ($keys as $cell) {
						$writer->writeElement($cell, $row[$cell]);
					}
					$writer->endElement();	// data

				}
				$writer->endElement(); // root
				break;
			default:
			  header("Content-type: application/json; charset=utf-8");
			  print_r(json_encode($data));
		}
	}
	
	# 处理中心
	public function onModuleLoad(){
		if(!isset($_REQUEST[APIsParameter::token])){
			echo $this->onMessage(0);
			return;
		}
		if(!strtolower($_REQUEST[APIsParameter::token]) == strtolower($this->token)){
			echo $this->onMessage(0);
			return;
		}
		
		if(isset($_REQUEST[APIsParameter::order])){
			$this->order = $_REQUEST[APIsParameter::order];
		}
		
		if(!isset($_REQUEST[APIsParameter::type])){
			$this->type = OutputType::json;
		}else{
			$this->type = $_REQUEST[APIsParameter::type];
		}
		
		$arrJson;
		switch ($this->order)
		{
			case Orders::ApiListAll:
				$arrJson = $this->ApiListAll();
				break;
			case Orders::getBankListAllForSelect:
				$arrJson = $this->dbBankListAllForSelect();
				break;
			case Orders::getProductListAllForSelect:
			  	$arrJson = $this->dbProductListAllForSelect();
			  	break;
			case Orders::addNewSaleData:
				$arrJson = $this->dbAddNewSaleData();
				break;
			case Orders::getSoldList:
				$arrJson = $this->dbSoldList(SoldListType::all,1);
				break;
			case Orders::deleteSoldDataBySoldId:
				$arrJson = $this->dbDeleteSoldDataBySoldId();
				break;
			case Orders::setSoldSend:
				$arrJson = $this->dbSoldSend();
				break;
			case Orders::getSoldDataById:
				$arrJson = $this->dbSoldDataById();
				break;
			case Orders::getSoldLen:
				$arrJson = $this->dbSoldLen();
				break;
			#default:
			#$arrJson = array("returnValue"=>"noCommand");
		}
		switch ($this->type)
		{
			case OutputType::json:
				$this->onSetOutput($arrJson,OutputType::json);
				break;
			case OutputType::xml:
				$this->onSetOutput($arrJson,OutputType::xml);
				break;
			default:
			  	$this->onSetOutput($arrJson,OutputType::json);
		}
	}
}
$_APIs = new APIs();
$_APIs->onModuleLoad();
?>